import React, { Component } from 'react';
import styles from './index.css';
import { connect } from 'dva';
import { Button, message } from 'antd';
import { RouteComponentProps } from 'react-router-dom';
import { Dispatch, AnyAction } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { getDeviceDetail, addDevice } from '@/services/device';
import { BaseForm, ImgAndRemarkForm, OtherForm } from './components';
import _ from 'lodash';
import { DeviceInfo } from '@/models/device';
import produce, { Draft } from 'immer';

interface FormProps extends RouteComponentProps<{ deviceTypeNo: string; deviceId?: string }> {
  dispatch: Dispatch<AnyAction>;
}
interface FormState {
  deviceInfo: DeviceInfo;
}

class Form extends Component<FormProps, FormState> {
  baseForm: FormComponentProps['form'] | undefined | null = undefined;
  otherForm: FormComponentProps['form'] | undefined | null = undefined;
  imgAndRemarkForm: FormComponentProps['form'] | undefined | null = undefined;

  state: FormState = {
    deviceInfo: {
      brandNo: '',
      createId: 0,
      createTime: '',
      deleteFalg: 0,
      departmentId: 0,
      deviceId: 0,
      deviceName: '',
      deviceState: 0,
      deviceTypeNo: 0,
      deviceTypeParentNo: 0,
      extendedField: '',
      firstTreeTypeId: 0,
      groupId: 0,
      mainImage: '',
      maintenanceCycle: '',
      model: '',
      stateCode: 0,
      positionDetails: '',
      productionCompany: '',
      productionTime: '',
      purchaseTime: '',
      remarks: '',
      serialNumber: '',
      serviceLife: '',
      sort: 0,
      specs: '',
      supplyCompany: '',
      treeTypeId: 0,
      unitNameId: 0,
      updateId: 0,
      updateTime: '',
      useTime: '',
      useUser: '',
    },
    passNodeData: [],
  };

  async componentDidMount() {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'device/getDeviceTypeNoOptions',
      payload: { deviceTypeNo: match.params.deviceTypeNo },
    });
    dispatch({
      type: 'device/getAreaOptions',
    });

    dispatch({ type: 'statistics/longDeviceType' });
    if (match.params.deviceId) {
      const [err, data] = await getDeviceDetail({ deviceId: match.params.deviceId });
      console.log(data);
      if (!err) {
        console.log(data, 77);
        this.setState(
          produce((draft: Draft<FormState>): void => {
            draft.deviceInfo = data;
          }),
          () => {
            dispatch({
              type: 'device/matchChildsByParents',
              payload: { deviceTypeNo: data.deviceTypeParentNo },
            }); // 再请求
          },
        );
      }
    }
  }

  onBaseFormCreate = (form?: FormComponentProps['form']) => {
    this.baseForm = form;
  };

  onOtherFormCreate = (form?: FormComponentProps['form']) => {
    this.otherForm = form;
  };

  onImgAndRemarkFormCreate = (form?: FormComponentProps['form']) => {
    this.imgAndRemarkForm = form;
  };
  qwe = () => {
    const { dispatch, history } = this.props;
    dispatch({ type: 'device/clearChildren' });
    history.goBack();
  };
  handleSubmit = async () => {
    const { match } = this.props;
    if (!this.otherForm || !this.baseForm || !this.imgAndRemarkForm) return;
    const validList = await Promise.all(
      this.asyncFun(this.otherForm, this.baseForm, this.imgAndRemarkForm),
    );
    let p = { extendedField: JSON.stringify(validList.shift()) };

    let o = _.reduce(validList, (prev, cur) => _.assign({}, prev, cur));

    o = _.assign({}, p, o);

    if (match.params.deviceId) o = _.assign({}, { deviceId: match.params.deviceId }, o);
    o.firstTreeTypeId = o.treeTypeId[0];
    o.treeTypeId = o.treeTypeId[o.treeTypeId.length - 1];
    const [err, data, msg] = await addDevice(o);
    if (!err) message.info(msg);
  };

  asyncFun = (...forms: FormComponentProps['form'][]) => {
    return _.map(
      forms,
      form =>
        new Promise((resolve, reject) => {
          form.validateFields((err: any, value: any) => {
            if (!err) resolve(value);
          });
        }),
    );
  };

  handleReset = () => {
    this.baseForm && this.baseForm.resetFields();
    this.otherForm && this.otherForm.resetFields();
    this.imgAndRemarkForm && this.imgAndRemarkForm.resetFields();
  };
  // 从baseform中拿到资产种类带出的extendfield值
  getChildsItemNode = (data: any) => {
    this.setState(
      produce((draft: Draft<FormState>): void => {
        draft.passNodeData = data;
      }),
      () => {
        console.log(data);
      },
    );
  };
  render() {
    const { match, history } = this.props;
    const { deviceInfo } = this.state;
    const titleStyle = {
      position: 'absolute',
      top: '-25px',
      left: 0,
      color: '#e0dcdc',
    };
    const deviceTypeNo = +match.params.deviceTypeNo;
    const deviceId = match.params.deviceId;
    return (
      <div className={styles.container}>
        {deviceId ? (
          <span style={titleStyle}>位置: 编辑设备</span>
        ) : (
          <span style={titleStyle}>位置: 添加设备</span>
        )}
        <div className={styles.box}>
          <div className={styles.wrapper}>
            <div className={styles.tag}>
              <span className={styles.title}>基本信息</span>
            </div>
            <BaseForm
              onCreate={this.onBaseFormCreate}
              deviceInfo={deviceInfo}
              deviceTypeParentNo={match.params.deviceTypeNo}
              passNodeWay={this.getChildsItemNode}
            />
          </div>
          <div className={styles.wrapper}>
            <div className={styles.tag}>
              <span className={styles.title}>备注</span>
            </div>
            <ImgAndRemarkForm onCreate={this.onImgAndRemarkFormCreate} deviceInfo={deviceInfo} />
          </div>
          <div className={styles.wrapper}>
            <div className={styles.tag}>
              <span className={styles.title}>其他信息</span>
            </div>
            <OtherForm
              onCreate={this.onOtherFormCreate}
              extendedField={this.state.passNodeData}
              deviceInfo={deviceInfo}
            />
          </div>
        </div>
        <div className={styles.btn}>
          <Button className={styles.antBtn1} onClick={this.handleSubmit}>
            提交
          </Button>
          {!deviceId && (
            <Button className={styles.antBtn2} onClick={this.handleReset}>
              清除
            </Button>
          )}
          <Button className={styles.antBtn3} onClick={this.qwe}>
            取消
          </Button>
        </div>
      </div>
    );
  }
}

export default connect()(Form);
